package com.changgou.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.changgou.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

@CanalEventListener
public class SpuListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /*
     * EntryType:当前操作的数据库类型
     *
     * RowData:当前操作数据库的数据
     * */
    @ListenPoint(schema = "changgou_goods",table = "tb_spu")
    public void goodUp(CanalEntry.EntryType entryType,CanalEntry.RowData rowData){
        //获取改变之前的数据 转换成map 便于封装
        Map<String,String> oldDate =new HashMap<>();
        rowData.getBeforeColumnsList().forEach((c)->oldDate.put(c.getName(),c.getValue()));

        //获取改变之后的数据 转换成map 便于封装
        Map<String,String> newDate =new HashMap<>();
        rowData.getAfterColumnsList().forEach((c)->newDate.put(c.getName(),c.getValue()));

        //获取最新上架的商品 0->1
        if("0".equals(oldDate.get("is_marketable"))&&"1".equals(newDate.get("is_marketable"))){
           //将商品的spuId 发送到mq
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",
                    newDate.get("id"));
        }

        //获取最新下架的商品
        if("1".equals(oldDate.get("is_marketable"))&&"0".equals(newDate.get("is_marketable"))){
            //将商品的spuId 发送到mq
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_DOWN_EXCHANGE,"",
                    newDate.get("id"));
        }

        //获取最新被审核通过的商品信息 status 0-》1
        if("0".equals(oldDate.get("status"))&&"1".equals(newDate.get("status"))){
            //将商品的spuId发送到mq
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",newDate.get("id"));
        }
    }
}
